package com.HuiShou.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.*;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.ResourceHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;


/**
 * DetectionService 类提供了与 Python 检测服务交互的功能。
 * 主要用于处理图像文件的上传和检测结果的解析。
 */
@Service
public class DetectionService {

    @Autowired
    private RestTemplate restTemplate;


    private static final String PYTHON_API_URL = "http://4a1a18c4.r31.cpolar.top/detect";

    /**
     * 调用 Python 检测服务对上传的图像文件进行处理，并返回检测结果。
     *
     * @param imageFile 上传的图像文件，类型为 MultipartFile
     * @return 包含检测结果的 Map，包含以下键值：
     *         - "processed_image": 处理后的图像数据
     *         - "labels": 检测到的标签列表
     *         - "scores": 检测到的置信度分数列表
     * @throws RuntimeException 如果 Python 服务返回错误状态码、空响应或响应字段缺失
     */
    public Map<String, Object> detectImage(MultipartFile imageFile) {
        try {
            // 构建多部分请求，设置请求头和请求体
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);

            ByteArrayResource fileResource = new ByteArrayResource(imageFile.getBytes()) {
                @Override
                public String getFilename() {
                    return imageFile.getOriginalFilename();
                }
            };

            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("file", fileResource);

            // 调用 Python 服务，发送 POST 请求
            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
            ResponseEntity<Map> response = restTemplate.exchange(
                    PYTHON_API_URL,
                    HttpMethod.POST,
                    requestEntity,
                    Map.class
            );

            // 检查响应状态码是否成功
            if (!response.getStatusCode().is2xxSuccessful()) {
                throw new RuntimeException("Python服务返回错误状态码: " + response.getStatusCodeValue());
            }

            // 显式类型转换并检查类型安全性
            Map responseBodyRaw = response.getBody();
            if (responseBodyRaw == null) {
                throw new RuntimeException("Python服务返回的响应体不是有效的 Map 类型");
            }

            @SuppressWarnings("unchecked")
            Map<String, Object> responseBody = responseBodyRaw;

            // 提取并验证响应中的结构化数据
            return Map.of(
                    "processed_image", requireNonNull(responseBody.get("image_output")),
                    "labels", requireNonNull((List<?>) responseBody.get("labels")).stream()
                            .map(Object::toString)
                            .collect(Collectors.toList()),
                    "scores", requireNonNull((List<?>) responseBody.get("scores")).stream()
                            .map(obj -> Double.parseDouble(obj.toString()))
                            .collect(Collectors.toList())
            );

        } catch (HttpStatusCodeException e) {
            // 处理 HTTP 错误响应
            String errorBody = e.getResponseBodyAsString();
            throw new RuntimeException("Python服务错误: " + errorBody);
        } catch (Exception e) {
            throw new RuntimeException("处理失败: " + e.getMessage(), e);
        }
    }

    /**
     * 检查对象是否为非空，如果为空则抛出异常。
     *
     * @param obj 待检查的对象
     * @param <T> 对象的类型
     * @return 非空的对象
     * @throws RuntimeException 如果对象为 null
     */
    private static <T> T requireNonNull(T obj) {
        if (obj == null) {
            throw new RuntimeException("响应字段缺失");
        }
        return obj;
    }
}
//@Service
//public class DetectionService {
//
//    @Autowired
//    private RestTemplate restTemplate;
//
//    private static final String PYTHON_API_URL = "http://localhost:5000/detect";
//
//    public Map detectViaApi(String imagePath) {
//        try {
//            Map<String, String> request = Collections.singletonMap("image_path", imagePath);
//            ResponseEntity<Map> response = restTemplate.postForEntity(PYTHON_API_URL, request, Map.class);
//
//            if (response.getStatusCode().is2xxSuccessful()) {
//                return response.getBody();
//            } else {
//                throw new RuntimeException("API 调用失败，状态码：" + response.getStatusCode().value());
//            }
//        } catch (Exception e) {
//            throw new RuntimeException("调用检测 API 时发生错误：" + e.getMessage(), e);
//        }
//    }
//}